package tt.dz.appserver.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

import tt.dz.appserver.entity.vo.AccessToken;
import tt.dz.appserver.entity.vo.JSSign;
import tt.dz.appserver.util.date.DateUtil;
import tt.dz.appserver.util.http.HttpUtils;


public class RefreshUtil {

	private static final Logger LOG = Logger.getLogger("[微信token刷新保存]:");
	// 最近一次访问时间
	//public static Date last_Visit_Date = new Date();
	// 微信服务器刷新频率
	//public static int expires_in = 1;
	// 最近异常访问微信服务器时间， 主动刷新会访问一次，其他模块刷新可能也会访问异常
	//public static Date last_Visit_Weixin_Date = new Date();
	// 微信服务器token
	//public static String access_token = "";

	
	
	// 最近js一次访问时间
	//public static Date last_Visit_Date_js = new Date();
	// 微信服务器刷新频率
	//public static int expires_in_js = 1;
	// 最近异常访问微信服务器时间， 主动刷新会访问一次，其他模块刷新可能也会访问异常
	//public static Date last_Visit_Weixin_Date_js = new Date();
	// 微信服务器token
	//public static String jsapi_ticket = "";

	public static Map<String, Map<String,Object>> map = new HashMap<String, Map<String,Object>>();

	public static Map<String,Object>  init(String mercharntCode){
		Map<String,Object> detail = new HashMap<String,Object>();
		detail.put("last_Visit_Date",  new Date() );
		detail.put("expires_in", 1);
		detail.put("last_Visit_Weixin_Date", new Date());
		detail.put("access_token", "");
		detail.put("last_Visit_Date_js", new Date());
		detail.put("expires_in_js", 1);
		detail.put("last_Visit_Weixin_Date_js", new Date());
		detail.put("jsapi_ticket", "");
		map.put(mercharntCode, detail);
		return detail;
	}

	/**
	 * 更新微信服务器token,
	 */
	/*
	 * public static void updateAccessToken(String appid,String secret){
	 * 
	 * }
	 */

	/**
	 * 
	 * @param resoure
	 *            数据来源：微信QQ等
	 * @param merchantCode
	 *            系统嘛，如华体等等
	 * @return
	 */
	public static AccessToken getMerAccessToken(String resoure, String merchantCode, JSSign sign) {

		// 允许进入获取token,必须是已配置的数据来源或者系统码
		List<String> list = allowEnter(resoure, merchantCode);
		if (list == null) {
			return null;
		}
		AccessToken acctoken = new AccessToken();
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("grant_type", "client_credential");
		paramMap.put("appid", list.get(0));
		paramMap.put("secret", list.get(1));
		sign.setAppId(list.get(0));
		LOG.info("appid=" + list.get(0) + "secret=" + list.get(1));
		/**
		 * 1.如果刷新时间为1，说明第一次进入系统 2.进入系统的时间与微信上传访问时间大于2小时,保证用户使用，服务器间隔1小时访问一次
		 */
		Map<String,Object> parmMap = map.get(merchantCode);
		LOG.info("当前获取到的参数集合【"+parmMap +"】");
		if(parmMap==null){
			parmMap=init(merchantCode);
		}
		/**
		 * 变量初始化
		 */
		int  expires_in = 1;
		Date last_Visit_Weixin_Date = new Date();
		String access_token = "";
		
		expires_in = (int) parmMap.get("expires_in");
		last_Visit_Weixin_Date = (Date) parmMap.get("last_Visit_Weixin_Date");
		LOG.info("当前过期时间：["+expires_in+"]");
		if (expires_in == 1 || (((new Date()).getTime() - last_Visit_Weixin_Date.getTime()) > expires_in * 500)) {
			
			LOG.info("需要访问微信官网："+((new Date()).getTime() - last_Visit_Weixin_Date.getTime()));
			
			String token = HttpUtils.getRequest(Constants.weixinUrl.WeiXin_token, paramMap);
			JSONObject getTokenRelust = JSONObject.parseObject(token);
			LOG.info("访问access_token[" + token + "];");
			access_token = getTokenRelust.getString("access_token");
			parmMap.put("access_token", access_token);
			if (access_token == null || access_token.equals("")) {
				LOG.info("访问access_token异常[" + token + "];");
				return acctoken;
			}
			expires_in = getTokenRelust.getInteger("expires_in");
			parmMap.put("expires_in", expires_in);
			parmMap.put("last_Visit_Date", new Date());
			parmMap.put("last_Visit_Weixin_Date", new Date());
		} else {
			// 2小时内访问刷新异常token
			parmMap.put("last_Visit_Date", new Date());
		}
		access_token = (String) parmMap.get("access_token");
		acctoken.setToken(access_token);
		Date valid = (Date) parmMap.get("last_Visit_Weixin_Date");
		valid.setHours(valid.getHours() - 1);
		acctoken.setValidDate(DateUtil.getDateTime(valid));
		return acctoken;
	}

	//
	public static List<String> allowEnter(String resoure, String merchantCode) {
		List<String> code = new ArrayList<String>();
		if (ConverUtil.checkDataSource(resoure, merchantCode) == 1) {
			String huatiapiKey = Constants.huatiWeixinApiKey;
			String huatisecret = Constants.huatiWeixinSecret;
			code.add(huatiapiKey);
			code.add(huatisecret);
			return code;
		} else if (ConverUtil.checkDataSource(resoure, merchantCode) == 2) {
			String dianzhuangapiKey = Constants.dianzhuangWeixinApiKey;
			String dianzhuangsecret = Constants.dianzhuangWeixinSecret;
			code.add(dianzhuangapiKey);
			code.add(dianzhuangsecret);
			return code;
		}
		return null;
	}

	public static String getJSTicket(String resoure, String merchantCode, JSSign sign) {

		AccessToken accessToken = getMerAccessToken(resoure, merchantCode, sign);

		if (accessToken.getToken() == null || accessToken.getToken().equals("")) {
			LOG.error("访问getJSTicket异常;resoure=【" + resoure + "】，merchantCode=【" + merchantCode + "】");
			return "";
		}
		/**
		 * 1.如果刷新时间为1，说明第一次进入系统 2.进入系统的时间与微信上传访问时间大于2小时,保证用户使用，服务器间隔1小时访问一次
		 */
		Map<String,Object> parmMap = map.get(merchantCode);
		
		LOG.info("获取getJSTicket是渠道的固定参数：【"+parmMap+"】");
		if(parmMap == null){
			parmMap=init(merchantCode);
		}
		
		/**
		 * 初始化变量
		 */
		int expires_in_js = 1;
		Date last_Visit_Weixin_Date_js = new Date();
		String jsapi_ticket = "";
		
		expires_in_js = (int) parmMap.get("expires_in_js");
		last_Visit_Weixin_Date_js = (Date) parmMap.get("last_Visit_Weixin_Date_js");
		
		if (expires_in_js == 1
				|| (((new Date()).getTime() - last_Visit_Weixin_Date_js.getTime()) > expires_in_js * 500)) {
			
			LOG.info("需要访问微信时间间隔："+((new Date()).getTime() - last_Visit_Weixin_Date_js.getTime()));
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("access_token", accessToken.getToken());
			paramMap.put("type", "jsapi");

			String token = HttpUtils.getRequest(Constants.weixinUrl.WEIXIN_TICKET, paramMap);

			LOG.info("访问获取用户的jsapi_ticket返回数据[" + token + "];");

			JSONObject getTokenRelust = JSONObject.parseObject(token);

			parmMap.put("last_Visit_Date_js", new Date());
			Integer errcode = getTokenRelust.getInteger("errcode");
			if (errcode == null || errcode != 0) {
				LOG.error("访问getJSAccessToken异常;resoure=【" + resoure + "】，merchantCode=【" + merchantCode + "】");
				return "";
			}
			jsapi_ticket = getTokenRelust.getString("ticket");			
			parmMap.put("jsapi_ticket", jsapi_ticket);
			
			expires_in_js = getTokenRelust.getInteger("expires_in");
			parmMap.put("expires_in_js", expires_in_js);
			
			
			parmMap.put("last_Visit_Weixin_Date_js", new Date());
		} else {
			// 2小时内访问刷新异常token
			parmMap.put("last_Visit_Date_js", new Date());
		}
		//map.put(merchantCode, parmMap);
		return (String) parmMap.get("jsapi_ticket");
	}
	public static void main(String[] args) {
		map.get("");
	}

}
